package com.lean.android.ad.repository.impl

import com.lean.android.ad.network.NetworkFactory
import com.lean.android.ad.repository.AdRepository
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.model.AdEventRequestBody
import com.lean.android.ad.repository.model.AdSwitchInfo
import com.lean.android.ad.repository.service.AdApiService
import com.lean.android.network.ResultTransformer
import kotlinx.coroutines.flow.Flow
import com.lean.android.network.Result
import retrofit2.create


internal class AdRepositoryImpl : AdRepository {

    private val adService: AdApiService by lazy {
        NetworkFactory.createRetrofit().create()
    }

    override fun loadAdInfo(): Flow<Result<AdSwitchInfo>> {
        return ResultTransformer.asResultFlow(networkCall = {
            adService.loadAdInfo()
        }, successCall = {
            it.data.save()
        })
    }

    override suspend fun reportAdEvent(
        requestId: String,
        eventType: ReportHelper.AdEventType,
        platformId: String,
        adPosition: ReportHelper.AdPositionType,
        cpm: Int,
        errorCode: String
    ): Result<Any> {
        return ResultTransformer.asResult(networkCall = {
            adService.reportAdEvent(
                AdEventRequestBody(
                    platform = platformId,
                    traceId = requestId,
                    adPosition = adPosition.posId,
                    errorCode = errorCode,
                    ecpm = cpm,
                    eventType = eventType.eventType
                )
            )
        })
    }

    override suspend fun reportAppDuration(duration: Long): Result<Any> {
        return ResultTransformer.asResult(
            networkCall = {
                adService.reportAppDuration(hashMapOf("time" to duration))
            }
        )
    }
}